#include "myhttpd.h"
#include "create_socket.h"

extern s_configuration *g_config;

/*
** Create the first socket, nonblocking, which allow new connections
** Return the socket, -1 if KO
*/
int create_socket(void)
{
  int mysocket = -1;

  mysocket = socket(AF_INET, SOCK_STREAM, 0);
  if (load_config_socket(&mysocket))
  {
    listen(mysocket, 5);
    set_non_blocking(mysocket);
  }

  return (mysocket);
}


/*
** Load configuration necessary to bind the socket
** We have to call this function when the port is changed
** Return : 0 = KO, 1 = OK
*/
int load_config_socket(int *mysocket)
{
  struct sockaddr_in	tmp_struct;
  struct sockaddr	*socket_struct;
  void			*tmp;
  int			result = 0;

  if (*mysocket != -1)
  {
    tmp = &tmp_struct;
    tmp_struct.sin_family = AF_INET;
    tmp_struct.sin_port = htons(g_config->port);
    tmp_struct.sin_addr.s_addr = htonl(INADDR_ANY);
    socket_struct = tmp;

    if (bind (*mysocket, socket_struct, sizeof (struct sockaddr_in)) != -1)
      result = 1;
  }

  return (result);
}


/*
** Allow to a socket to became nonblocking during accept()
*/
void set_non_blocking(int mysocket)
{
  int opts;

  /*
  ** Take out flags of my socket
  */
  opts = fcntl(mysocket,F_GETFL);
  if (opts < 0)
    exit(EXIT_FAILURE);

  /*
  ** Add the flag 0_NONBLOCK
  */
  opts = (opts | SO_REUSEADDR);
  if (fcntl(mysocket,F_SETFL,opts) < 0)
    exit(EXIT_FAILURE);
 }
